package com.mininglamp.hbga.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.log4j.helpers.FileWatchdog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

public class ConfigHelper extends Properties {

    private static final long serialVersionUID = 1L;

    public static final Logger log = LoggerFactory.getLogger(ConfigHelper.class);
    public static final String APP_CONF_DIR = System.getProperty("app.conf.dir", "");
    public static final ConfigHelper INSTANCE = new ConfigHelper();

    private ConfigHelper() {
        super();

        File dir = new File(APP_CONF_DIR);
        Preconditions.checkState(dir.exists() && dir.isDirectory(),
            "The app.conf.dir is not exists or is not directory.");

        for (File file : dir.listFiles((file, name) -> name.endsWith(".properties"))) {
            // 对配置文件添加监视
            new FileWatchdog(file.getAbsolutePath()) {
                @Override
                protected void doOnChange() {
                    loading(filename);
                }
            }.start();
        }
    }

    private void loading(String filename) {
        log.info("Loading property file {}", filename);
        try (FileInputStream fis = new FileInputStream(filename)) {
            load(fis);
        } catch (Exception e) {
            log.error("Loading property file failed.", e);
        }
    }

}
